package app.database.connection;                   

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @class Class that manipulate all database connection and generate a reference
 * to that connection applying singleton pattern
 * @author Sweetie - 2012
 */
public class MySQLConnector 
{
    //Standard database connection
    private static Connection connection;
    
    /**
     * Method used to get a database connection
     * @return a database connection reference
     */
    public static Connection getConnection() 
    {
        if (connection == null)
        {
            try 
            {
                String driverName = "com.mysql.jdbc.Driver";                        
                Class.forName(driverName);

                String serverName = "localhost";    //caminho do servidor do BD
                String mydatabase ="mysql";        //nome do seu banco de dados
                String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
                String username = "root";        //nome de um usuário de seu BD      
                String password = "panda";      //sua senha de acesso
                connection = DriverManager.getConnection(url, username, password);

                return connection;
            } 
            catch (ClassNotFoundException e) 
            {
                System.out.println(e.getMessage());
                return null;
            } 
            catch (SQLException e) 
            {
                System.out.println(e.getMessage());
                return null;
            }
        }
        return connection;
    }
    
    /**
     * Method used to close a database connection
     * @return success or failure of the connection close action 
     */
    public static boolean closeConnection() 
    {
        try 
        {
            MySQLConnector.getConnection().close();
            return true;
        } 
        catch (SQLException e) 
        {
            return false;
        }
    }
}